<template>
  <div class="category-list">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>课程分类管理</span>
          <el-button type="primary" @click="handleAdd">添加分类</el-button>
        </div>
      </template>

      <el-table
        :data="categoryList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" :maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-switch
            v-model="categoryForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { CourseCategory } from '@/types/api/course'
import { courseApi } from '@/api/modules/course'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const categoryList = ref<CourseCategory[]>([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const categoryFormRef = ref()
const currentCategoryId = ref(0)

// 表单数据
const categoryForm = reactive({
  name: '',
  description: '',
  status: 1
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
}

// 获取分类列表
const getCategoryList = async () => {
  loading.value = true
  try {
    const response = await courseApi.getCourseCategories()
    categoryList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 添加分类
const handleAdd = () => {
  dialogTitle.value = '添加分类'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(categoryForm, {
    name: '',
    description: '',
    status: 1
  })
}

// 编辑分类
const handleEdit = (row: CourseCategory) => {
  dialogTitle.value = '编辑分类'
  isEdit.value = true
  dialogVisible.value = true
  currentCategoryId.value = row.id
  // 填充表单数据
  Object.assign(categoryForm, {
    name: row.name,
    description: row.description,
    status: row.status
  })
}

// 删除分类
const handleDelete = (row: CourseCategory) => {
  formUtils.handleDeleteConfirm(`分类 "${row.name}"`, async () => {
    await courseApi.deleteCourseCategory(row.id)
    getCategoryList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存分类信息
const handleSave = async () => {
  if (!categoryFormRef.value) return

  await categoryFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      const submitKey = isEdit.value ? `update_category_${currentCategoryId.value}` : 'create_category'

      try {
        await preventDuplicateSubmit(submitKey, async () => {
          saveLoading.value = true
          try {
            if (isEdit.value) {
              // 编辑分类
              await courseApi.updateCourseCategory(currentCategoryId.value, {
                name: categoryForm.name,
                description: categoryForm.description,
                status: categoryForm.status
              })
              ElMessage.success('更新成功')
            } else {
              // 添加分类
              await courseApi.createCourseCategory({
                name: categoryForm.name,
                description: categoryForm.description
              })
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            getCategoryList()
          } catch (error: any) {
            ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
            throw error // 重新抛出错误以确保防重复提交正确处理
          } finally {
            saveLoading.value = false
          }
        })
      } catch (error: any) {
        // 防重复提交保护捕获的错误
        if (error.message === '请勿重复提交') {
          ElMessage.warning('请勿重复提交')
        }
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(categoryFormRef.value, categoryForm, {
    name: '',
    description: '',
    status: 1
  })
}

// 初始化
onMounted(() => {
  getCategoryList()
})
</script>

<style scoped lang="scss">
.category-list {
  .category-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
